import re

# 遍历从 1 到 80
for i in range(1, 81):
    # 生成文件名，确保编号为两位数字，如 01、02 等
    chapter_num = str(i).zfill(2)
    file_name = f"chapter{chapter_num}.txt"
    try:
        # 以只读模式打开文件，读取文件内容
        with open(file_name, 'r', encoding='utf-8') as file:
            content = file.read()
        # 使用正则表达式替换掉英文字母、方括号、等于号和 <> 符号
        new_content = re.sub(r'[a-zA-Z\[\]<> =\”\"\'“’‘]', '', content)
        # 以写入模式打开文件，将处理后的内容写回文件
        with open(file_name, 'w', encoding='utf-8') as file:
            file.write(new_content)
        print(f"已处理 {file_name}")
    except FileNotFoundError:
        print(f"未找到文件 {file_name}")
    except Exception as e:
        print(f"处理 {file_name} 时出现错误: {e}")

# 遍历 chapter01.txt 到 chapter80.txt
for i in range(1, 81):
    # 格式化文件名
    chapter_num = str(i).zfill(2)  # 将数字转换为两位字符串，如 1 转换为 01
    file_path = f"chapter{chapter_num}.txt"
    output_file = f"chapter{chapter_num}.wav"

    try:

        # 读取文本文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()

        prev = ""
        new_lines = []
        for line_num, line in enumerate(lines):
            line = line.strip()
            if line:
                # 为每行生成唯一的临时音频文件名
                if len(line) < 10:
                    prev += line.strip('\r\n ')
                    #MUST add chinese end symbol or the audio output will be noises.
                    prev += "。"
                else:
                    print(f"line content: {prev + line} end")
                    new_lines.append(prev + line + '。\n')
                    prev = ""
        if prev!="":
           new_lines.append(prev + '\n')
           prev = ""

        with open(file_path, 'w', encoding='utf-8') as file:
            file.writelines(new_lines)
            
    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
    except Exception as e:
        print(f"处理 {file_path} 时发生未知错误：{e}")
